package org.luxor.commons.rabbitmq.service.pushmessage;

import com.rabbitmq.client.Channel;
import org.luxor.commons.core.constant.BaseConst;
import org.luxor.commons.core.utils.Jackson2Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author Mr.Yan  @date 2019/10/16$
 */
@Component
public class UserChangeEventReceiver {
    private static final Logger log = LoggerFactory.getLogger(UserChangeEventReceiver.class);

    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = "exchange.topic.user", type = "topic"),
            key = "user.chang",
            value = @Queue("queue.user.change")
    ))
    public void receiveQueue(String message, Channel channel,
                             @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag,
                             @Header(BaseConst.TOKEN_NAME) String token) throws IOException {
        UserChangeEvent msg = Jackson2Utils.toBean(message, UserChangeEvent.class);
        log.info("<<< 收到一个用户改变事件. Token=[{}]  message=[{}] ", token, msg);
        // 确认消息
        channel.basicAck(deliveryTag, false);
    }

}